<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户信息表</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f9f9f9;
            color: #333;
        }

        h1 {
            text-align: center;
            color: #444;
        }

        table {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
        }

        th {
            background-color: #007bff;
            color: white;
            font-weight: bold;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        tr:hover {
            background-color: #e9e9e9;
        }

        td {
            border-bottom: 1px solid #ddd;
        }

        .container {
            text-align: center;
        }
    </style>
</head>
<body>
<h1>用户信息表</h1>
<div class="container">
    <?php
    // 数据库连接配置
    $host = 'localhost'; // 数据库服务器地址
    $dbname = 'test'; // 数据库名
    $user = 'root'; // 数据库用户名
    $password = 'root'; // 数据库密码

    try {
        // 创建 PDO 实例，连接数据库
        $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
        // 设置错误模式为异常
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "<p style='color: green;'>连接成功</p>";

        // 查询用户表信息
        $sql = "SELECT * FROM user";
        $stmt = $pdo->query($sql);

        // 输出用户信息
        echo "<table>";
        echo "<tr><th>ID</th><th>Name</th><th>Age</th></tr>";
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row['id']) . "</td>";
            echo "<td>" . htmlspecialchars($row['name']) . "</td>";
            echo "<td>" . htmlspecialchars($row['age']) . "</td>";
            echo "</tr>";
        }
        echo "</table>";

    } catch (PDOException $e) {
        // 捕获异常并输出错误信息
        echo "<p style='color: red;'>连接失败: " . $e->getMessage() . "</p>";
    }
    ?>
</div>
</body>
</html>
